package com.smartwork.common.sequence;

import java.sql.Connection;
import java.util.Date;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.smartwork.common.sequence.bytecode.SequenceCreator;
import com.smartwork.common.utils.SpringContextHolder;

public class SequenceManager {
	/**
	 * 日志对象
	 */
	protected static Logger logger = LoggerFactory.getLogger(SequenceManager.class);
	
	private SequenceManager() throws Exception {
	}
	
	/**
	 * 取到数据库连接
	 * 
	 * @return Connection
	 */
	private static Connection getConnection() throws Exception {
	    
		DataSource ds = (DataSource) SpringContextHolder.getBean("SeqDataSource");
		return ds.getConnection();
	}

	/**
	 * 通过Key取到sequence
	 * @param tableName sequence表名
	 * @return seqNo
	 */
	public static String getSequence(String tableName) {
		Connection conn;
		String seqNo = "";
		try {
			conn = getConnection();
			
			Sequence seq = SequenceCreator.getSequence(tableName);
			
			seqNo = seq.getNextValue(conn);
		} catch (Exception e) {
			logger.error("Sequence error ! {}", e.getMessage());
			
		}
		return seqNo;
	}

	public static void main(String[] args) throws Exception {
		String[] keys = new String[] { "t_broker.id" };
		System.out.println(new Date());
		for (int i = 0; i < keys.length; i++) {
			String sequence = SequenceManager.getSequence(keys[i]);
			System.out.println(keys[i] + " : " + sequence);
		}
		System.out.println(new Date());
	}
}
